/*
 * @Descripttion: 
 * @Author: voanit
 * @Date: 2022-06-08 17:58:49
 * @LastEditors: voanit
 * @LastEditTime: 2022-06-09 12:26:06
 */
import { ApiResponse, Suggestion, Article } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import request from '@/utils/request'

export const getSuggestion = (keyword: string): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{ options: Suggestion }>>(
      '/suggestion',
      {
        params: {
          q: keyword,
        },
      }
    )

    dispatch({ type: 'search/suggestion', payload: res.data.data.options })
  }
}
export const addHistory = (keyword: string): RootThunkAction => {
  return async (dispatch, getState) => {
    let history = getState().search.searchHistory.filter(item => item !== keyword)
    history.unshift(keyword)
    if (history.length > 10) {
      history = history.slice(0, 10)
    }
    // console.log(history, 99999);

    dispatch({ type: 'search/history', payload: history })
  }
}


export const delHistory = (keyword: string): RootThunkAction => {
  return async (dispatch, getState) => {
    let newHistory = getState().search.searchHistory.filter(item => item !== keyword)

    dispatch({ type: 'search/delHistory', payload: newHistory })
    // dispatch({ type: 'search/history', payload: newHistory })
  }
}
export const delAllHistory = (): RootThunkAction => {


  return async (dispatch) => {

    dispatch({ type: 'search/delAllHistory', payload: [] })
    // dispatch({ type: 'search/history', payload: [] })
  }
}


/**
 * 获取搜索结果数据
 */
export const getSearchResult = (q: string, page: number = 1, per_page: number = 10): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{ page: number, per_page: number, total_count: number, results: Article[] }>>('/search', {
      params: {
        q,
        page,
        per_page
      }
    })
    console.log(res, 5);

    dispatch({
      type: 'search/result',
      payload: res.data.data,
    })
  }
}